package com.crowntit.domain.trade.service.settlement.filter;

import com.crowntit.domain.trade.adapter.repository.ITradeRepository;
import com.crowntit.domain.trade.model.entity.GroupBuyOrderListEntity;
import com.crowntit.domain.trade.model.entity.GroupBuyTeamEntity;
import com.crowntit.domain.trade.model.entity.TradeSettlementRuleBackEntity;
import com.crowntit.domain.trade.model.entity.TradeSettlementRuleCommandEntity;
import com.crowntit.domain.trade.service.settlement.factory.TradeSettlementRuleFilterFactory;
import com.crowntit.types.design.framework.link.model2.handler.ILogicHandler;
import com.crowntit.types.enums.ResponseCode;
import com.crowntit.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class TradeSettlementValidTimeRuleFilter implements ILogicHandler<TradeSettlementRuleCommandEntity, TradeSettlementRuleFilterFactory.DynamicContext, TradeSettlementRuleBackEntity> {

    @Resource
    private ITradeRepository repository;

    @Override
    public TradeSettlementRuleBackEntity apply(TradeSettlementRuleCommandEntity requestParam, TradeSettlementRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
        log.info("支付时间有效性检测");
        GroupBuyOrderListEntity groupBuyOrderList = dynamicContext.getGroupBuyOrderList();
        GroupBuyTeamEntity groupBuyTeamEntity = repository.queryGroupBuyOrderTeamByTeamId(groupBuyOrderList.getTeamId());

        Date current = new Date();
        Date validStartTime = groupBuyTeamEntity.getValidStartTime();
        Date validEndTime = groupBuyTeamEntity.getValidEndTime();

        if (current.before(validStartTime) || current.after(validEndTime)){
            throw new AppException(ResponseCode.E0106.getCode(), ResponseCode.E0106.getInfo());
        }
        return TradeSettlementRuleBackEntity.builder()
                .activityId(groupBuyTeamEntity.getActivityId())
                .status(groupBuyTeamEntity.getStatus())
                .notifyEntity(groupBuyTeamEntity.getNotifyEntity())
                .completeCount(groupBuyTeamEntity.getCompleteCount())
                .targetCount(groupBuyTeamEntity.getTargetCount())
                .lockCount(groupBuyTeamEntity.getLockCount())
                .teamId(groupBuyTeamEntity.getTeamId())
                .source(groupBuyTeamEntity.getSource())
                .channel(groupBuyTeamEntity.getChannel())
                .validStartTime(groupBuyTeamEntity.getValidStartTime())
                .validEndTime(groupBuyTeamEntity.getValidEndTime())
                .build();
    }
}
